package com.qf.Web.Filter;

import com.qf.Domain.User;
import com.qf.Service.Impl.UserServiceImpl;
import com.qf.Service.UserService;
import com.qf.Utils.Base64Utils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/*
 *
 */
@WebFilter(filterName = "AutoFilter",value = "/index.jsp")
public class AutoFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        User user = (User) request.getSession().getAttribute("user");
        if (user!=null){
            chain.doFilter(req, resp);
            return;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies!=null){
            for (Cookie cookie : cookies) {
                if (cookie.equals("userInfo")){
                    String value = Base64Utils.decode(cookie.getValue());
                    UserService userService=new UserServiceImpl();
                    try {
                        User LoginUser = userService.select(value.split("#")[0], value.split("#")[1]);
                        if (user!=null){
                            request.getSession().setAttribute("user", LoginUser);
                        }else {
                            Cookie cookie1=new Cookie("userInfo", "");
                            cookie1.setPath(request.getContextPath());
                            cookie1.setMaxAge(0);
                            response.addCookie(cookie1);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Cookie cookie1=new Cookie("userInfo", "");
                        cookie1.setPath(request.getContextPath());
                        cookie1.setMaxAge(0);
                        response.addCookie(cookie1);
                    }
                }
            }
        }
        chain.doFilter(req, resp);
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
